package cn.unknowpupil.init.configure.mybatisplus;



import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;


/**
 * 处理新增和更新的基础数据填充，配合BaseEntity和MyBatisPlusConfig使用。
 *
 * @Classname: MetaHandler
 * @Author: <a> w10g </a>
 * @CreateDate: Create in 2020/4/29 11:35
 * @Description:
 * @Version: 1.0
 */
@Component
public class MetaHandler implements MetaObjectHandler {
    private static final Logger logger = LoggerFactory.getLogger(MetaHandler.class);
    public static final String UPDATE_DATE = "updateTime";
    public static final String CREATE_DATE = "createTime";
    public static final String CREATOR = "createBy";
    public static final String EDITOR = "updateBy";
    public static final String VERSION = "version";
    public static final String STATUS = "status";
    public static final String DEL_FLAG = "delFlag";


    /**
     * 功能描述: <br>
     * 〈 新增数据执行〉
     *
     * @auther: w10g
     * @Date: 2020/4/29 19:49
     * @since: 1.0.0
     * @Param: metaObject {@link MetaObject}
     * @return: void
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Date date = new Date();

        logger.info(" -------------------- start insert fill 插入方法实体填充...  --------------------");
        if (metaObject.hasGetter(CREATE_DATE) ) {
            this.setFieldValByName(CREATE_DATE, date, metaObject);

        }
        if (metaObject.hasGetter(UPDATE_DATE)) {
            this.setFieldValByName(UPDATE_DATE, date, metaObject);
        }

        if (metaObject.hasGetter(VERSION) ) {
            this.setFieldValByName(VERSION, 0, metaObject);

        }
        if(metaObject.hasGetter(DEL_FLAG)){
            this.setFieldValByName(DEL_FLAG, 0, metaObject);
        }


    }

    /**
     * 功能描述: <br>
     * 〈 更新数据执行 MetaObject 的构造器是私有的,只提供 forObject 创建MetaObject对象〉
     *
     * @auther: w10g
     * @Date: 2020/4/29 19:49
     * @since: 1.0.0
     * @Param: metaObject {@link MetaObject}
     * @return: null
     */
    @Override
    public void updateFill(MetaObject metaObject) {

        logger.info(" -------------------- start update fill 更新方法实体填充 ...  --------------------");
        if (metaObject.hasGetter(UPDATE_DATE)) {
            this.setFieldValByName(UPDATE_DATE, new Date(), metaObject);
        }


    }

}